//
//  ProCityUtil.swift
//  ANOA
//
//  Created by 邱仙凯 on 2025/2/24.
//  Copyright © 2025 zwb. All rights reserved.
//  省市  一个接口  

import UIKit
import JJCollectionViewRoundFlowLayout_Swift

 

class ProCityUtil: UIViewController {
    
    init(selectType: CitySelectType,selectMode:CitySelectMode = .single) {
        super.init(nibName: nil, bundle: nil)
        self.selectType = selectType
        self.selectMode = selectMode

    }
  
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var multiArr:[(String,String,String)] = []
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        let sectionW = self.view.ks_width - 24
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.itemSize = CGSize(width: sectionW/4 - 0.5, height: 40)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 18, left: 12, bottom: 16, right: 12)
        
        // 2.创建UICollectionView
        let v = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        v.backgroundColor = .white
        v.showsHorizontalScrollIndicator = false
        
        v.register(ProCitySelectCell.self, forCellWithReuseIdentifier: ProCitySelectCell.identifier)
 
        return v
    }()
    
    var table1:UITableView!
    var table2:UITableView!
    var table3:UITableView!
    
    var province: SProCityModel?
    var city: SCityModel?
    var district: SProCityCountryModel?
    
    var citySelectClosure:((String,String)->())?
    var tripleSelectClosure:((String,String,String)->())?
    var multiTripleSelectClosure:(([(String,String,String)])->())?

    var selectType = CitySelectType.city
    var selectMode = CitySelectMode.single

    
    var s_proArr = [SProCityModel]()
    var s_cityDic = [String: [String: [String]]]()
    
    var cityArr = [SCityModel]()
    var districtArr = [SProCityCountryModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "城市选择"
        let leftBtn = UIButton.creat4Item(title: "返回") { _ in
           self.closeAction()
       }
        let left = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = left
        
        if s_proArr.count == 0 {
            KSNetwork.shared.doRequest(API.getAreaJson) { (data:BaseResult<SProCityModel>) in
                if data.flag == TRUE {
                    if let infos = data.infoArrCombine {
                        
                        var proArr = infos.filter { $0.namex == "福建省" }
                        self.province = proArr.first
                        proArr.append(contentsOf: infos.filter { $0.namex != "福建省" })
                        self.s_proArr = proArr
                        
                        self.cityArr = infos.first!.city_arr
                  
                        self.config()
                    }
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        } else {
            config()
        }
     
    }
    
    func getCityA(proName: String) {
        
        let tA = s_proArr.filter({ $0.namex.unwrap == proName })
        if tA.first != nil {
            cityArr = tA.first!.city_arr
        } else {
            cityArr = []
        }
    }
    
    func config() {

        
        if selectMode == .multi {
            let rightBtn = UIButton.creat4Item(title: "确定") { _ in
                guard self.multiArr.count > 0 else {
                    KSToast("未选择")
                    return
                }
                if let clo = self.multiTripleSelectClosure {
                    clo(self.multiArr)
                }
                
                
                self.closeAction()
           }
            let right = UIBarButtonItem(customView: rightBtn)
            self.navigationItem.rightBarButtonItem = right
        }
        
        
        getCityA(proName: s_proArr[0].namex.unwrap)
        
 
        var ccH:CGFloat = 0
        if selectMode == .multi {
             ccH = 180
            collectionView.dataSource = self
            collectionView.delegate = self
            self.view.addSubview(collectionView)
            collectionView.snp.makeConstraints { make in
                make.left.right.top.equalToSuperview()
                make.height.equalTo(ccH)
            }
        }
        
       
        
        table1 = UITableView(frame: CGRect(x:0,y: ccH,width: 110,height: KSGlobal.screenH))
        table1.delegate = self
        table1.dataSource = self
        self.view.addSubview(table1)
        
        table2 = UITableView(frame: CGRect(x:111,y: ccH,width: KSGlobal.screenW - 111,height: KSGlobal.screenH))
        table2.tableFooterView = UIView()
        table2.delegate = self
        table2.dataSource = self
        self.view.addSubview(table2)
        
        
        table1.register(UITableViewCell.self, forCellReuseIdentifier: "provinceCell_1")
        table2.register(UITableViewCell.self, forCellReuseIdentifier: "cityCell_2")
        
        if self.selectType == .city {
            
        } else {
            table3 = UITableView(frame: CGRect(x:222,y: ccH,width: KSGlobal.screenW - 222,height: KSGlobal.screenH))
            table3.register(UITableViewCell.self, forCellReuseIdentifier: "districtCell_3")
            table3.tableFooterView = UIView()
            table3.delegate = self
            table3.dataSource = self
            self.view.addSubview(table3)
            
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            let visiCell = self.table1.visibleCells
            visiCell.first?.setSelected(true, animated: false)
        }
        
        
    }
    func closeAction() {
        if self.navigationController!.viewControllers.count > 1 { // 说明是push过来的
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: {
            })
        }
    }
}

extension ProCityUtil:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if tableView == table1 {
            return s_proArr.count
        } else if tableView == table2 {
            return cityArr.count
        } else {
            return districtArr.count
        }
        
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == table1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "provinceCell_1", for: indexPath)
            let pro = s_proArr[indexPath.row]
            cell.textLabel?.text = pro.namex
            cell.textLabel?.numberOfLines = 2
            
            return cell
        } else if tableView == table2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell_2", for: indexPath)
            let city = cityArr[indexPath.row]
            cell.textLabel?.text = city.namex
            cell.textLabel?.numberOfLines = 2
            
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "districtCell_3", for: indexPath)
            let dist = districtArr[indexPath.row]
            cell.textLabel?.text = dist.namex
            cell.textLabel?.numberOfLines = 2
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        

        if tableView == table1 {
            province = s_proArr[indexPath.row]
            getCityA(proName: province!.namex.unwrap)
            
            self.table2.reloadData()
            
        } else if tableView == table2 {
            
            city = cityArr[indexPath.row]
            
            if self.selectType == .city  {
                if let clo = citySelectClosure {
                    clo(province?.namex.unwrap ?? "" ,city?.namex.unwrap ?? "")
                }
                self.closeAction()
            } else  {
                
                if selectMode == .multi {
                    self.multiArr.append((province?.namex.unwrap ?? "" ,city?.namex.unwrap ?? "", ""))
                    districtArr = city?.country_arr ?? []
                    self.collectionView.reloadData()
                } else {
                    self.multiArr.append((province?.namex.unwrap ?? "" ,city?.namex.unwrap ?? "", ""))
                    districtArr = city?.country_arr ?? []
                    self.table3.reloadData()
                }
  
            }
        } else {
            if let clo = tripleSelectClosure {
                let dist = districtArr[indexPath.row]
                clo(province?.namex.unwrap ?? "" ,city?.namex.unwrap ?? "", dist.namex.unwrap)
            }
            self.closeAction()
        }
    }
    
}
// MARK: - 代理和数据源
extension ProCityUtil:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
     
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return multiArr.count
        
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProCitySelectCell.identifier, for: indexPath as IndexPath) as! ProCitySelectCell
        let shows = self.multiArr[indexPath.row].2 != "" ? self.multiArr[indexPath.row].2 : self.multiArr[indexPath.row].1
        cell.title.text = shows
  
         return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
 
        self.multiArr.remove(at: indexPath.row)
        self.collectionView.reloadData()
    }
    
    
    
    
}
extension ProCityUtil : JJCollectionViewDelegateRoundFlowLayout_Swift {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 12, left: 12, bottom: 12, right: 12)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init()
        model.cornerRadius = 8
        model.backgroundColor = UIColor(kshex:"#f9f9f9")
        
        
        return model;
        
    }
}
import ObjectMapper
struct SProCityModel: Mappable {
    
    var id_key: String?
    var namex: String?
    var city_arr = [SCityModel]()

    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        id_key <- map["id_key"]
        namex <- map["name"]
        city_arr <- map["city"]

    }
}

struct SCityModel: Mappable {
    
    var id_key: String?
    var namex: String?
    var country_arr = [SProCityCountryModel]()

    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        id_key <- map["id_key"]
        namex <- map["name"]
        country_arr <- map["country"]

    }
}



struct SProCityCountryModel: Mappable {
    
    var id_key: String?
    var namex: String?

    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        id_key <- map["id_key"]
        namex <- map["name"]

    }
}
